#!/usr/bin/env python
# -*- coding: utf-8 -*-
#  post.py
#  description

#  Created by zhouzongli633 on 2020/8/13 4:52 下午.
#  Copyright ©Intellectus All rights reserved.


from rest_framework.views import APIView

from Baby.models import Users
from Common.logger import app_log
from Common.response import resp
from User.models import Posts, PostMedia
from User import user_helper


class PostView(APIView):

    def get(self, request, *args, **kwargs):
        try:
            user_id = request.GET.get("user_id", "")
            post_id = request.GET.get("post_id", "")
            ret = {}
            if not user_id or not post_id:
                return resp(4001)
            req_posts = Posts.objects.filter(id=post_id).first()

            if req_posts:
                ret = req_posts.posts_include_media_to_json()
            return resp(0, ret)
        except Exception as e:
            app_log.exception(e)
            return resp(str(e))

    def post(self, request, *args, **kwargs):
        try:
            ret = {}
            params = request.data
            user_id = params['user_id']
            post_text = params['post_text']
            post_pictures = params['post_pictures']
            if not user_id or (not post_text and not post_pictures):
                return resp(400, 'Invalid Data')
            user = Users.objects.get(id=user_id)
            if not user:
                return resp(400, 'Invalid Data')
            post = Posts(
                post_text=post_text,
                user_id=user_id
            )
            post.save()
            for it in post_pictures:
                p_m = PostMedia(
                    post=Posts.objects.filter(user_id=user_id, post_text=post_text).last(),
                    file_name=it,
                    thumbnail=it,
                )
                p_m.save()
            family = user_helper.get_all_family_members(user_id)
            req_posts = Posts.objects.filter(user_id__in=family).all()
            posts = [post.posts_include_media_to_json() for post in req_posts]
            ret['posts'] = posts

            return resp(0, ret)
        except Exception as e:
            app_log.exception(e)
            return resp(-1, str(e))
